package com.unis.controller.es;

/*************************************************************************
 Copyright (C) Unpublished Unis Software, Inc. All rights reserved.
 Unis Software, Inc., Confidential and Proprietary.

 This software is subject to copyright protection
 under the laws of the Public of China and other countries.

 Unless otherwise explicitly stated, this software is provided
 by Unis "AS IS".
 *************************************************************************/

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.unis.common.annotation.ESField;
import com.unis.common.annotation.ESTable;
import com.unis.common.listener.MyApplicationListener;
import com.unis.common.util.TimeUtil;
import com.unis.service.es.EsService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.*;

/**
 *
 */
@Controller
@RequestMapping("/es/es")
public class EsController {

    final Logger log = LoggerFactory.getLogger(EsController.class);

    @Value("${es.listStyle}")
    private String listStyle;
    @Value("${es.nameStyle}")
    private String nameStyle;
    @Value("${es.valueStyle}")
    private String valueStyle;
    @Resource
    private EsService esService;

    //全文检索页面
    @RequestMapping("/pageNew.html")
    public String forwordNew(ModelMap map, @RequestParam Map<?, ?> paramMap) throws Exception {
        map.put("paramMap", paramMap);
        return "es/qwjsPage";
    }

  /*  @RequestMapping("/searchResult.html")
    public String searchResult(ModelMap map, String tab, String gjz) throws Exception {
        gjz = gjz.replace("：", ":");
        map.put("gjz", gjz);
        map.put("tab", tab);
        List<Map> list = new ArrayList();
        Map esClassCache = MyApplicationListener.esClassCache;
        for (Object key : esClassCache.keySet()) {
            JSONObject tabjsonObject = esService.getEsData(key.toString(), gjz, 0);
            Map m = new HashMap();
            m.put("id", key.toString());
            m.put("name", getZyName(key.toString()));
            if (tabjsonObject.get("hits") == null) {
                m.put("num", "0");
            } else {
                m.put("num", ((JSONObject) tabjsonObject.get("hits")).get("total").toString());
            }
            list.add(m);
        }
        map.put("esTabList", list);
        return "es/qwjsResultPage";
    }
*/
    @RequestMapping("/searchResult.html")
    public String searchResult(ModelMap map, String tab, String gjz) throws Exception {
        gjz = gjz.replace("：", ":");
        map.put("gjz", gjz);
        map.put("tab", tab);
        List<Map> list = new ArrayList();
        Map esClassCache = MyApplicationListener.esClassCache;
        for (Object key : esClassCache.keySet()) {
            SearchResponse searchResponse = esService.getEsData(key.toString(), gjz, -1);
            Map m = new HashMap();
            m.put("id", key.toString());
            m.put("name", getZyName(key.toString()));
            if (searchResponse == null || searchResponse.getHits() == null) {
                m.put("num", "0");
            } else {
                m.put("num", searchResponse.getHits().getTotalHits());
            }
            list.add(m);
        }
        map.put("esTabList", list);
        return "es/qwjsResultPage";
    }

   /* @RequestMapping("/qwjsList.html")
    public String qwjsList(ModelMap map, String tab, String gjz, String page) throws Exception {
        gjz = gjz.replace("：", ":");
        map.put("gjz", gjz);
        map.put("zyname", getZyName(tab));
        JSONObject tabjsonObject = esService.getEsData(tab, gjz, Integer.parseInt(page));
        Class aClass = MyApplicationListener.esClassCache.get(tab);
        StringBuffer html;
        String cjsj = "";
        String timestamp = "";
        String v = "";
        Date d;
        if (tabjsonObject != null && tabjsonObject.getJSONObject("hits") != null) {
            JSONArray hitsJsonObject = tabjsonObject.getJSONObject("hits").getJSONArray("hits");
            for (int i = 0; i < hitsJsonObject.size(); i++) {
                cjsj = "";
                html = new StringBuffer(1000);
                JSONObject hitsJsonArray = hitsJsonObject.getJSONObject(i);
                JSONObject _sourceJsonObject = hitsJsonArray.getJSONObject("_source");
                hitsJsonArray.remove("_source");

                for (Field field : aClass.getDeclaredFields()) {
                    field.setAccessible(true);
                    if (field.isAnnotationPresent(ESField.class)) {

                        ESField eSField = field.getAnnotation(ESField.class);
                        if (StringUtils.isNotBlank(eSField.text()) || eSField.showTime()) {
                            d = _sourceJsonObject.getDate("@timestamp");
                            timestamp = TimeUtil.fmtDate(d, "");
                            if (field.getGenericType().toString().equals("class java.util.Date")) {
                                d = _sourceJsonObject.getDate((StringUtils.isNotBlank(eSField.name()) ? eSField.name() : field.getName()).toLowerCase());
                                v = TimeUtil.fmtDate(d, "");
                            } else {
                                v = _sourceJsonObject.getString((StringUtils.isNotBlank(eSField.name()) ? eSField.name() : field.getName()).toLowerCase());
                            }
                            if (StringUtils.isBlank(v)) {
                                v = "-";
                            }
                            if (StringUtils.isNotBlank(eSField.text())) {
                                html.append(MessageFormat.format(nameStyle, eSField.text()));
                                html.append(MessageFormat.format(valueStyle, v));
                            }
                            if (eSField.showTime()) {
                                cjsj = v;
                            }
                        }

                    }
                }
                cjsj = StringUtils.isNotBlank(cjsj) ? cjsj : timestamp;
                hitsJsonArray.put("esShow", MessageFormat.format(listStyle, i + 1, cjsj, html.toString()));
            }
        }
        map.put("esData", tabjsonObject);
        return "es/qwjsList";
    }
*/
    @RequestMapping("/qwjsList.html")
    public String qwjsList(ModelMap map, String tab, String gjz, int total, int page) throws Exception {
        gjz = gjz.replace("：", ":");
        map.put("gjz", gjz);
        int pageNum = total % 10 == 0 ? total / 10 : (total / 10) + 1;
        page = page > pageNum ? pageNum : page;
        page = page < 1 ? 1 : page;
        map.put("pageNum", pageNum);
        map.put("total", total);
        map.put("tab", tab);
        map.put("page", page);
        map.put("pageStart", (page - 3 < 1) ? 1 : page - 3);
        map.put("pageEnd", (page + 3 > pageNum) ? pageNum : page + 3);
        map.put("zyname", getZyName(tab));
        SearchResponse searchResponse = esService.getEsData(tab, gjz, (page));
        Class aClass = MyApplicationListener.esClassCache.get(tab);
        StringBuffer html;
        String cjsj = "";
        String timestamp = "";
        String v = "";
        Date d;
        List esData = new ArrayList();
        if (searchResponse != null && searchResponse.getHits() != null) {
            SearchHit[] hitsJsonObject = searchResponse.getHits().getHits();
            for (int i = 0; i < hitsJsonObject.length; i++) {
                cjsj = "";
                html = new StringBuffer(1000);
                SearchHit hitsJsonArray = hitsJsonObject[i];
//                Map<String, Object> _sourceJsonObject = hitsJsonArray.getSourceAsMap();
                String sourceAsString = hitsJsonArray.getSourceAsString();
                JSONObject _sourceJsonObject = (JSONObject) JSONObject.parse(sourceAsString);
                for (Field field : aClass.getDeclaredFields()) {
                    field.setAccessible(true);
                    if (field.isAnnotationPresent(ESField.class)) {

                        ESField eSField = field.getAnnotation(ESField.class);
                        if (StringUtils.isNotBlank(eSField.text()) || eSField.showTime()) {
                            d = _sourceJsonObject.getDate("@timestamp");
                            timestamp = TimeUtil.fmtDate(d, "");
                            if (field.getGenericType().toString().equals("class java.util.Date")) {
                                d = _sourceJsonObject.getDate((StringUtils.isNotBlank(eSField.name()) ? eSField.name() : field.getName()).toLowerCase());
                                v = TimeUtil.fmtDate(d, "");
                            } else {
                                v = _sourceJsonObject.getString((StringUtils.isNotBlank(eSField.name()) ? eSField.name() : field.getName()).toLowerCase());
                            }
                            if (StringUtils.isBlank(v)) {
                                v = "-";
                            }
                            if (StringUtils.isNotBlank(eSField.text())) {
                                html.append(MessageFormat.format(nameStyle, eSField.text()));
                                html.append(MessageFormat.format(valueStyle, v));
                            }
                            if (eSField.showTime()) {
                                cjsj = v;
                            }
                        }

                    }
                }
                cjsj = StringUtils.isNotBlank(cjsj) ? cjsj : timestamp;
                esData.add(MessageFormat.format(listStyle, (i + 1) + ((page-1)*10), cjsj, html.toString()));
            }
        }
        map.put("esData", JSON.toJSON(esData));
        return "es/qwjsList";
    }

    private String getZyName(String key) {
        return MyApplicationListener.esClassCache.get(key).getDeclaredAnnotation(ESTable.class).text();
    }


}

